package com.weizhi.system.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.weizhi.server.dto.Constant;
import com.weizhi.server.dto.ResponseDto;
import com.weizhi.server.dto.UserDto;
import com.weizhi.server.service.UserService;
import com.weizhi.server.util.JsonUtil;
import com.weizhi.server.util.UuidUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("admin/user")
public class UserController {

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);
    public final static String BUSINESS_NAME = "用户";

    @Autowired
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    @RequestMapping("list")
    public ResponseDto list(HttpServletRequest req) {
        JSONObject param = JsonUtil.convertRequest(req);
        logger.info("userController-list, param={}", param);
        PageInfo pageInfo = userService.list(param);
        return ResponseDto.createBySuccess(pageInfo);
    }

    @RequestMapping("all")
    public ResponseDto list() {
        logger.info("userController-all");
        List<UserDto> userDtoList = userService.all();
        return ResponseDto.createBySuccess(userDtoList);
    }

    @RequestMapping("save")
    public ResponseDto save(@RequestBody UserDto user) {
        logger.info("userController-save, user={}", user);

        if(StringUtils.isBlank(user.getName())) throw new RuntimeException("请求参数异常");

        user.setPassword(encryPassword(user.getPassword()));
        userService.save(user);
        return ResponseDto.createBySuccess();
    }

    @RequestMapping("editPassword")
    public ResponseDto editPassword(@RequestBody UserDto user) {
        logger.info("userController-editPassword, user={}", user);

        if(StringUtils.isBlank(user.getPassword())) throw new RuntimeException("请求参数异常");

        user.setPassword(encryPassword(user.getPassword()));
        userService.editPassword(user);
        return ResponseDto.createBySuccess();
    }

    @RequestMapping("login")
    public ResponseDto login(@RequestBody UserDto user, HttpServletRequest req) {
        if(StringUtils.isBlank(user.getUsername())) throw new RuntimeException("请求参数异常");
        if(StringUtils.isBlank(user.getPassword())) throw new RuntimeException("请求参数异常");

//        String imageCode = (String)req.getSession().getAttribute(user.getImageCodeToken());
//        req.getSession().removeAttribute(user.getImageCodeToken());
        String imageCode = (String) redisTemplate.opsForValue().get(user.getImageCodeToken());

        if(imageCode == null) throw new RuntimeException("验证码已过期");
        if(!imageCode.toLowerCase().equals(user.getImageCode().toLowerCase())) throw new RuntimeException("验证码不正确");

        redisTemplate.delete(user.getImageCodeToken());

        user.setPassword(encryPassword(user.getPassword()));
        UserDto userDto = userService.login(user);
//        req.getSession().setAttribute(Constant.SESSION_USER, userDto);
        String token = Constant.USER_TOKEN + UuidUtil.getShortUuid();
        userDto.setToken(token);
        redisTemplate.opsForValue().set(token, JSONObject.toJSONString(userDto), 36000, TimeUnit.SECONDS);
        userDto.setPassword(null);
        return ResponseDto.createBySuccess(userDto);
    }



    private String encryPassword(String password) {
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }

    @RequestMapping("logout/{token}")
    public ResponseDto logout( @PathVariable("token") String token) {
        logger.info("userController-logout, token={}", token);
        redisTemplate.delete(token);
        return ResponseDto.createBySuccess();
    }


    @DeleteMapping("/delete/{id}")
    public ResponseDto delete(@PathVariable Long id) {
        logger.info("userController-delete, id={}", id);
        userService.delete(id);
        return ResponseDto.createBySuccess();
    }
}

